/*
 * Copyright (C) 2012 CNL - ECE Dept - National University of Singapore
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package sg.nus.ece.cnl.veracity.common;

import com.xensource.xenapi.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import sg.nus.ece.cnl.veracity.access.SshUserCredentials;
import sg.nus.ece.cnl.veracity.access.TargetServer;
import sg.nus.ece.cnl.veracity.exception.VeracityException;

/**
 *
 * @author tram
 */
public class SessionBase {

    private static final Logger log = Logger.getLogger(SessionBase.class);
    // connection for this session
    private Connection connection;
    // the target physical server
    private TargetServer targetServer;
    private SshUserCredentials userCredentials;

    public SessionBase(TargetServer target, SshUserCredentials userCredentials) {
        this.targetServer = target;
        this.userCredentials = userCredentials;
    }

    /**
     * Connect to the server and open a session for manipulating VMs
     *
     * @throws VeracityException
     */
    public void connect() throws sg.nus.ece.cnl.veracity.exception.VeracityException {

        try {

            log.info("Creating the connection to server \"" + targetServer.getHostname() + "\" ...");
            connection = new Connection(new URL("http://" + targetServer.getHostname()));
            log.info("Connection to server \"" + targetServer.getHostname() + "\" successfully created.");

            log.info("Opening a new session on server \"" + targetServer.getHostname()
                    + "\" for the user \"" + userCredentials.getLogin() + "\" ...");
            Session.loginWithPassword(connection, userCredentials.getLogin(), userCredentials.getPassword(), APIVersion.latest().toString());
            log.info("Session for user \"" + userCredentials.getLogin() + "\" successfully created.");

        } catch (java.net.MalformedURLException ex) {
            // exception when creating the connection to the server
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        } catch (com.xensource.xenapi.Types.XenAPIException ex) {
            // exception throwed by the XEN API
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        } catch (org.apache.xmlrpc.XmlRpcException ex) {
            // exception throwed by the XmlRpc
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        }
    }

    /**
     * Disconnect from the server
     *
     * @throws VeracityException
     */
    public void disconnect() throws sg.nus.ece.cnl.veracity.exception.VeracityException {

        log.info("Disposing connection for the server \"" + targetServer.getHostname() + "\" ...");

        try {
            Session.logout(connection);
        } catch (com.xensource.xenapi.Types.XenAPIException ex) {
            // exception throwed by the XEN API
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        } catch (org.apache.xmlrpc.XmlRpcException ex) {
            // exception throwed by the XmlRpc
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        }
    }

    /**
     * Given a task in progress, sleeps until it completes, waking to print
     * status reports periodically.
     */
    /**
     * Given a task in progress, sleeps until it completes, waking to print
     * status reports periodically.
     *
     * @param task Task to wait
     * @param delay Time interval for delaying
     * @throws VeracityException Exception thrown when connection problem occurs
     */
    public void waitForTask(Task task, int delay) 
            throws sg.nus.ece.cnl.veracity.exception.VeracityException {

        try {
            while (task.getStatus(this.connection) == Types.TaskStatusType.PENDING) {
                log.info("Progress of task \"" + task.getNameDescription(this.connection) + "\":"
                        + task.getProgress(this.connection));
                Thread.sleep(delay);
            }
        } catch (com.xensource.xenapi.Types.XenAPIException ex) {
            // exception throwed by the XEN API
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        } catch (org.apache.xmlrpc.XmlRpcException ex) {
            // exception throwed by the XmlRpc
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        } catch (java.lang.InterruptedException ex) {
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        }
    }

    /**
     * Get the default Storage Repository
     *
     * @return
     * @throws VeracityException
     */
    public SR getDefaultStorageRepository() 
            throws sg.nus.ece.cnl.veracity.exception.VeracityException {

        try {
            Set<Pool> pools = Pool.getAll(connection);
            Pool pool = (pools.toArray(new Pool[0]))[0];
            return pool.getDefaultSR(connection);
        } catch (com.xensource.xenapi.Types.XenAPIException ex) {
            // exception throwed by the XEN API
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        } catch (org.apache.xmlrpc.XmlRpcException ex) {
            // exception throwed by the XmlRpc
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        }
    }

    /**
     * Get the VM template with associated template name label
     *
     * @param templateNameLabel the name label of the template
     * @return the VM template
     * @throws VeracityException
     */
    public VM getVMTemplate(String templateNameLabel) 
            throws sg.nus.ece.cnl.veracity.exception.VeracityException {

        try {
            Map<VM, VM.Record> all_recs = VM.getAllRecords(connection);
            for (Map.Entry<VM, VM.Record> e : all_recs.entrySet()) {
                if (e.getValue().isATemplate && e.getValue().nameLabel.contains(templateNameLabel)) {
                    return e.getKey();
                }
            }
        } catch (com.xensource.xenapi.Types.XenAPIException ex) {
            // exception throwed by the XEN API
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        } catch (org.apache.xmlrpc.XmlRpcException ex) {
            // exception throwed by the XmlRpc
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        }

        // no vm template corresponds to this name
        return null;
    }

    /**
     * Getting all VM templates stored on the server
     *
     * @return a list containing all VM templates
     * @throws VeracityException
     */
    public List<VM> getAllVMTemplates() 
            throws sg.nus.ece.cnl.veracity.exception.VeracityException {

        List<VM> vmTemplates = new ArrayList<VM>();

        try {
            Map<VM, VM.Record> all_recs = VM.getAllRecords(connection);
            for (Map.Entry<VM, VM.Record> e : all_recs.entrySet()) {
                if (e.getValue().isATemplate) {
                    vmTemplates.add(e.getKey());
                }
            }
        } catch (com.xensource.xenapi.Types.XenAPIException ex) {
            // exception throwed by the XEN API
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        } catch (org.apache.xmlrpc.XmlRpcException ex) {
            // exception throwed by the XmlRpc
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        }

        return vmTemplates;
    }

    /**
     * Get the network associated with a name label
     *
     * @param networkNameLabel name label of the network
     * @return network
     * @throws VeracityException
     */
    public Network getNetwork(String networkNameLabel) 
            throws sg.nus.ece.cnl.veracity.exception.VeracityException {

        try {
            Set<Network> networks = Network.getAll(connection);
            for (Network net : networks) {
                if (net.getNameLabel(connection).equalsIgnoreCase(networkNameLabel)) {
                    return net;
                }
            }
        } catch (com.xensource.xenapi.Types.XenAPIException ex) {
            // exception throwed by the XEN API
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        } catch (org.apache.xmlrpc.XmlRpcException ex) {
            // exception throwed by the XmlRpc
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        }

        return null;
    }

    /**
     * Get all network on the server
     *
     * @return list of network on the server
     * @throws VeracityException
     */
    public List<Network> getAllNetworks() 
            throws sg.nus.ece.cnl.veracity.exception.VeracityException {

        List<Network> listNetworks = new ArrayList<Network>();
        try {
            Set<Network> networks = Network.getAll(connection);
            for (Network net : networks) {
                listNetworks.add(net);
            }

        } catch (com.xensource.xenapi.Types.XenAPIException ex) {
            // exception throwed by the XEN API
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        } catch (org.apache.xmlrpc.XmlRpcException ex) {
            // exception throwed by the XmlRpc
            throw new sg.nus.ece.cnl.veracity.exception.VeracityException(ex);
        }

        return listNetworks;
    }

    public Connection getConnection() {
        return connection;
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    public TargetServer getTargetServer() {
        return targetServer;
    }

    public void setTargetServer(TargetServer targetServer) {
        this.targetServer = targetServer;
    }
}
